package net.huadong.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 接收请求连接处理
 */
public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> {

    /**
     * 当通道接收到accept请求成功后
     * @param result
     * @param attachment
     */
    @Override
    public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) {

        //已经注册成功了，为啥还要再次调用accept方法？
        //为了监听后续其他用户的链接的请求，形成循环
        attachment.asynchronousServerSocketChannel.accept(attachment, this);


        //构建缓冲区对象
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //调用通道的read监听，实例一个handler，处理read操作 ReadCompletionHandler
        result.read(byteBuffer, byteBuffer, new ReadCompletionHandler(result));
    }

    @Override
    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
        exc.printStackTrace();
        attachment.latch.countDown();
    }
}
